package com.example.mplayer.screens

import android.app.Activity
import android.content.pm.ActivityInfo
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.widget.FrameLayout
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.media3.common.MediaItem
import androidx.media3.common.MimeTypes
import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
import androidx.media3.ui.PlayerView
import android.view.View
import android.view.WindowManager
import android.widget.ImageButton
import com.example.mplayer.R
import com.example.mplayer.player.CustomHlsDataSourceFactory
import androidx.activity.compose.BackHandler

private const val PRIVATE_KEY = """
-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCqBiDGXjht0KcC
gQZdgVEvJFkVL/2x2nVeaHH5c7plWSEEDH7LN8dhpaSHXRqWPST1YCymmZVRzzE9
Pf6f2yptBLfu5cfZtN+1Hun6H+ZPvDn9YFKSPYzJ5xxG1HouT+Uf1kvAad2LCMTN
7fEFyrqjup4EKYp7K6mcl5Yi+JVr9f0fm4C3tJPnJZWVU0bXcVJknNMsLi171pkx
vYnPAdJjWyR5Tq5XQIwTZ9aEDC47N3eKEUBy1TObLw9rsHdLe5dxM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ibipAI5OPXMOv0CEYQEdi2q8u3fmCU
uF+OMm42p9efPBEHLsKtdZM+TU5K915F5wOX2R0CgYB5xpwpSJ3fXf0Scx8yCeVP
xPtUZm6/10+bTtqTbWwx2vcvHFfBHyG7pi+Hys+eZXyBugJxFidcoIzXbcvBOpZR
aQ5MVzeSzRmTec7Hz9YNXaf+wRbxtVay/nYfBIcs5SyPMEvrJPhoftkEIdWw0ovj
vaw0hkS4mxFYXxwX0jvhPg==
-----END PRIVATE KEY-----
"""

@UnstableApi
@Composable
fun VideoPlayerScreen(
    videoUrl: String,
    videoTitle: String,
    onBackClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    val context = LocalContext.current
    var isFullscreen by remember { mutableStateOf(false) }
    val activity = context as Activity
    val view = LocalView.current

    // 处理返回按键
    BackHandler {
        if (isFullscreen) {
            isFullscreen = false
        } else {
            activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
            onBackClick()
        }
    }

    // 处理全屏状态变化
    DisposableEffect(isFullscreen) {
        if (isFullscreen) {
            // 进入全屏
            activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
            activity.window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
            view.systemUiVisibility = (View.SYSTEM_UI_FLAG_FULLSCREEN
                    or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
        } else {
            // 退出全屏
            activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
            activity.window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
            view.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE
        }
        onDispose {
            activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
        }
    }

    val exoPlayer = remember {
        ExoPlayer.Builder(context)
            .setMediaSourceFactory(
                DefaultMediaSourceFactory(CustomHlsDataSourceFactory(context, PRIVATE_KEY))
            )
            .build()
    }

    DisposableEffect(videoUrl) {
        val mediaItem = MediaItem.Builder()
            .setUri(videoUrl)
            .setMimeType(MimeTypes.APPLICATION_M3U8)
            .build()
        
        exoPlayer.setMediaItem(mediaItem)
        exoPlayer.prepare()
        exoPlayer.playWhenReady = true

        onDispose {
            exoPlayer.release()
        }
    }

    Column(modifier = modifier.fillMaxSize()) {
        // 非全屏时显示顶部栏
        if (!isFullscreen) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Icon(
                    painter = painterResource(id = R.drawable.ic_back),
                    contentDescription = "返回",
                    modifier = Modifier.clickable(onClick = onBackClick)
                )
                Text(text = videoTitle)
            }
        }

        AndroidView(
            factory = { context ->
                PlayerView(context).apply {
                    player = exoPlayer
                    layoutParams = FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT)
                    
                    // 添加全屏按钮到控制器
                    setControllerOnFullScreenModeChangedListener { fullscreen ->
                        isFullscreen = fullscreen
                    }
                    
                    // 自定义全屏按钮图标
                    findViewById<ImageButton>(androidx.media3.ui.R.id.exo_fullscreen).apply {
                        setImageResource(
                            if (isFullscreen) R.drawable.ic_fullscreen_exit
                            else R.drawable.ic_fullscreen
                        )
                    }
                }
            },
            modifier = Modifier.fillMaxSize(),
            update = { playerView ->
                // 更新全屏按钮图标
                playerView.findViewById<ImageButton>(androidx.media3.ui.R.id.exo_fullscreen).apply {
                    setImageResource(
                        if (isFullscreen) R.drawable.ic_fullscreen_exit
                        else R.drawable.ic_fullscreen
                    )
                }
            }
        )
    }
} 